package io;
import java.io.*;

import utils.*;

import java.util.*;
import java.util.Map.Entry;
public class LoadTrainData {
	private  final String trainFile = "D:/Users/Nova/Desktop/work/Rec/data/train.txt";
	List<UserInfo> allUserInfo;
	public void loadData(String fileName)	throws IOException{
		BufferedReader br = new BufferedReader(new FileReader(fileName));
		allUserInfo = new ArrayList<UserInfo>();
		String line = br.readLine();line = br.readLine();
		UserInfo currentUser = null;
		String previousId = "";
		int lineCount = 0;
		while(line!=null && line.length() > 0){
			String[] currentLines = line.split("\\s+");
			
			if(!previousId.equals(currentLines[0]))	{			//add the old user and create a new user
				if(currentUser!=null)
					allUserInfo.add(currentUser);
				currentUser = new UserInfo(currentLines[0]);
				previousId =  currentLines[0];
			}
			currentUser.addInteraction(currentLines[1], currentLines[3]);
			
			line = br.readLine();
			if(++lineCount%100000 == 0)
				System.out.println(lineCount + "line processed");
		}
		allUserInfo.add(currentUser);
		br.close();
		
	}
	public  void outPutUserInfoData(String fileName) throws IOException{
		BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
		Collections.sort(allUserInfo, UserInfo.getComparator());
		for(UserInfo user:allUserInfo)	{
			Iterator it = user.interactions.entrySet().iterator();
			while(it.hasNext()){
				Map.Entry<Integer, Interaction>  entry = (Entry<Integer, Interaction>) it.next();
				Interaction action = entry.getValue();
				bw.write(user.userId + " " + action.toString());bw.newLine();
			}
		}
		bw.close();
	}
	void wholeProcess() throws IOException	{
		loadData(trainFile);
		outPutUserInfoData("UserInteraction.txt");
		
	} 
	public static void main(String[] args) throws IOException	{
		new LoadTrainData().wholeProcess();
	}
}

